package mt.omid.dimomuth.mgm;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MgmProtocol implements Runnable
{

    private Socket     clntSock;
    private Logger     logger;
    private MgmHandler hndl;


    public MgmProtocol( Socket sock, Logger lgr, MgmHandler hndl )
    {
	this.clntSock = sock;
	this.logger = lgr;
	this.hndl = hndl;
    }

    public static void handleRequest( Socket sock, Logger lgr, MgmHandler hndl )
    {
	try
	{
	    BufferedReader reader = new BufferedReader( new InputStreamReader( sock
		    .getInputStream() ) );
	    BufferedWriter writer = new BufferedWriter( new OutputStreamWriter( sock
		    .getOutputStream() ) );

	    String recvMsg;
	    String reslMsg;

	    while( ( recvMsg = reader.readLine() ) != null )
	    {
		lgr.finest( "Mgm Msg received:" + recvMsg );
		if( recvMsg.matches( "exit|bye|quit|logout|logoff" ) )
		{
		    lgr.info( "Ending management session of client at " + sock.getInetAddress().getCanonicalHostName() );
		    break;
		}
		else
		{
		    reslMsg = hndl.processRequest( recvMsg );
		    lgr.finest( "Mgm Result sent:" + reslMsg );
		    writer.write( reslMsg );
		    writer.flush();
		}
	    }
	}
	catch( IOException ie )
	{
	    lgr.log( Level.WARNING, "Exception in Mgm Protocol", ie );
	}
	catch( Exception e )
	{
	    lgr.log( Level.WARNING, "General Exception in Mgm Protocol handling", e );
	}
	finally
	{
	    try
	    {
		sock.close();
	    }
	    catch( IOException ie )
	    {
		lgr.log( Level.WARNING, "Exception in closing socket.", ie );
	    }
	}
    }

    public void run()
    {
	handleRequest( clntSock, logger, hndl );
    }
}
